﻿
using IHISCETeim.BLL;
using IHISCETeim.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using IHISCETeim.Library;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;

namespace IHISCETeim.Web.AgentSys.PWMgr
{
    public partial class AgentPartOrderEdit : AgentPageBase
    {
        protected override Permission[] PowerKey
        {
            get
            {
                return new Permission[] { Permission.修改,Permission.新增, Permission.查看 };
            }
        }
        protected override string DWZRef
        {
            get { return "AgentPartOrderList"; }
        }

        protected int OrderId
        {
            get
            {

                return GetRequestValue<int>("OrderId", 0);
            }
        }
        /// <summary>
        /// 操作方式
        /// </summary>
        protected string action
        {
            get
            {

                return GetRequestValue<string>("action", "View");
            }
        }

        private AgentPartOrderInfo _obj = null;

        public AgentPartOrderInfo obj
        {
            get
            {
                if (_obj == null)
                {
                    if (OrderId == 0)
                    {
                        _obj = new AgentPartOrderInfo() { OrderNumber= "自动生成",
                            AgentName=base.User.RealName,
                            IssueDate =System.DateTime.Now,OrderState="",FaultDate= System.DateTime.Now,
                            AcceptName= GetLastPartsAccept("AcceptName"),
                            AcceptTel = GetLastPartsAccept("AcceptTel"),
                            AcceptAddress = GetLastPartsAccept("AcceptAddress")
                        };
                    }
                    else {
                        _obj = AgentPartOrderController.GetList(OrderId);
                    }
                }
                
                return _obj;
            }
        }

        private DataTable _lastPartsAcceptDt = null;
        protected string GetLastPartsAccept(string columnName)
        {
            if (_lastPartsAcceptDt == null)
                _lastPartsAcceptDt = AgentPartOrderController.GetLastAcceptInfo(base.User.UserId);
            if (_lastPartsAcceptDt.Rows.Count > 0)
                return _lastPartsAcceptDt.Rows[0][columnName].ToString();
            return "";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (GetRequestValue<string>("ajaxmethod", "") == "add")
            {
                add();
            }
           if (GetRequestValue<string>("ajaxmethod", "")== "edit")
            {
                edit("已审核",0);
            }
            if (GetRequestValue<string>("ajaxmethod", "") == "recheck")
            {
                recheck();
            }
            if (GetRequestValue<string>("ajaxmethod", "") == "cancel")
            {
                cancel();
            }
            if (GetRequestValue<string>("ajaxmethod", "") == "update")
            {
                edit(obj.OrderState,1);
            }
            
             //JsonConvert.SerializeObject(obj)
             LoadInfo();
        }

        private void LoadInfo()
        {

            List<AgentPartOrderDetailInfo> listParts = AgentPartOrderController.GetAllDetailByOrderId(OrderId);
            if (listParts.Count < 10)
            {
                int addNum = 10 - listParts.Count;
                while (addNum > 0)
                {
                    listParts.Add(new AgentPartOrderDetailInfo() { ID = addNum, BuyType = "", ShipType = "", Quantity = 1  });
                    addNum = addNum - 1;
                }
            }

            this.rpParts.DataSource = listParts;
            this.rpParts.DataBind();

        }

        protected string getImgPath(object imgpath)
        {
            return imgpath==null  ? "" : ResolveClientUrl(imgpath.ToString());
        }
        private void add()
        {
            AgentPartOrderInfo obj2 = Request.SerializableObject<AgentPartOrderInfo>();
            obj2.AgentId = base.User.UserId;
            obj2.AgentName = base.User.RealName;
            obj2.OrderState = "审核中";
            obj2.OrderTotal = 0;
            char[] caSplit = new char[] { ',' };
          

            //加载配件信息
            List<AgentPartOrderDetailInfo> partsList = new List<AgentPartOrderDetailInfo>();
            string[] ItemCodes = GetRequestValue<string>("ItemCode", "").Split(caSplit);
            string[] Dscriptions = GetRequestValue<string>("Dscription", "").Split(caSplit);
            string[] Quantitys = GetRequestValue<string>("Quantity", "").Split(caSplit);
            string[] BuyTypes = GetRequestValue<string>("BuyType", "").Split(caSplit);
            string[] ShipTypes = GetRequestValue<string>("ShipType", "").Split(caSplit);
            for (int index = 0; index < ItemCodes.Count(); index++)
            {
                if (ItemCodes[index] != "")
                {
                    AgentPartOrderDetailInfo pobj = new AgentPartOrderDetailInfo();
                    pobj.ItemCode = ItemCodes[index].Trim();
                    pobj.Dscription = Dscriptions[index];
                    pobj.Quantity = Convert.ToDecimal(Quantitys[index]);
                    pobj.BuyType = BuyTypes[index];
                    pobj.ShipType= ShipTypes[index];

                    decimal vatx = pobj.BuyType == "库存订货" ? 0.85m : 0.9m;
                    pobj.OldPrice = Convert.ToDecimal(SBOController.GetOITMAgentPrice(pobj.ItemCode));
                    pobj.Price = pobj.OldPrice * (1.17m)* vatx;//折后 含税单价
                    　
                    pobj.LineTotal = pobj.Quantity * pobj.Price;
                    obj2.OrderTotal += pobj.LineTotal;
                    partsList.Add(pobj);
                }
            }
            //这里处理是生成附属品情，还是重新提交
                if (obj.OrderState == "再确认")
                {
                    AgentPartOrderController.Delete(OrderId);
                }
              
                if (AgentPartOrderController.Add(obj2,partsList) > 0)
                {
                    SuccessJson(String.Format("已提交订单请求."),this.DWZRef);
                }
                else {
                    ErrorJson("提交订单请求失败！");
                }
           

        }

        private void edit(string OrderState,int type)
        {
            AgentPartOrderInfo obj2 = Request.SerializableObject<AgentPartOrderInfo>();
            obj2.OrderState = OrderState;// "已审核";
            obj2.UpdateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            obj2.OrderTotal = 0;
            char[] caSplit = new char[] { ',' };
            string checkitemcode = "", checkQuantity="", checkPrice="";

            //加载配件信息
            List<AgentPartOrderDetailInfo> partsList = new List<AgentPartOrderDetailInfo>();
            string[] ItemCodes = GetRequestValue<string>("ItemCode", "").Split(caSplit);
            string[] Dscriptions = GetRequestValue<string>("Dscription", "").Split(caSplit);
            string[] Quantitys = GetRequestValue<string>("Quantity", "").Split(caSplit);
            string[] BuyTypes = GetRequestValue<string>("BuyType", "").Split(caSplit);
            string[] ShipTypes = GetRequestValue<string>("ShipType", "").Split(caSplit);
            for (int index = 0; index < ItemCodes.Count(); index++)
            {
                if (ItemCodes[index] != "")
                {
                    if (!string.IsNullOrEmpty(ItemCodes[index]))
                    {
                        if (SBOController.GetHaveItemCode(ItemCodes[index]) == "")
                        {
                            checkitemcode += string.Format("物料号【{0}】　{1}<br/>", ItemCodes[index], Dscriptions[index].Trim());
                            continue;
                        }
                    }

                    AgentPartOrderDetailInfo pobj = new AgentPartOrderDetailInfo();
                    pobj.ItemCode =  ItemCodes[index].Trim();
                    pobj.Dscription = Dscriptions[index];
                    pobj.Quantity = Convert.ToDecimal(Quantitys[index]);

                    if (pobj.Quantity<=0)
                    {
                        checkQuantity += string.Format("物料号【{0}】<br/>", ItemCodes[index]);
                        continue;
                    }

                    pobj.BuyType = BuyTypes[index];
                    pobj.ShipType = ShipTypes[index];

                    decimal vatx = pobj.BuyType == "库存订货" ? 0.85m : 0.9m;
                    pobj.OldPrice = Convert.ToDecimal(SBOController.GetOITMAgentPrice(pobj.ItemCode));
                    pobj.Price = pobj.OldPrice * (1.17m) * vatx;//折后 含税单价　

                    if (pobj.Price <= 0)
                    {
                        checkPrice += string.Format("物料号【{0}】<br/>", ItemCodes[index]);
                        continue;
                    }

                    pobj.LineTotal = pobj.Quantity * pobj.Price;
                    obj2.OrderTotal += pobj.LineTotal;
                    partsList.Add(pobj);
                }
            }

            if (!string.IsNullOrEmpty(checkitemcode))
            {
                ErrorJson("以下配件不存在ERP系统中,请重新确认:<br/>" + checkitemcode);
                return;//表示有配件在ERP系统中不不存在
            }

            if (!string.IsNullOrEmpty(checkQuantity))
            {
                ErrorJson("以下配件订购数量小于0,请重新确认:<br/>" + checkQuantity);
                return;
            }
            if (!string.IsNullOrEmpty(checkPrice))
            {
                ErrorJson("以下配件订购价格小于0,请重新确认<br/>没有价格的情况，要么物料号有错误，要么在ERP系统未设置经销商销售价<br/>" + checkPrice);
                return;
            }
            //这里处理是生成附属品情，还是重新提交

            if (type == 0)
            {
                if (AgentPartOrderController.Update(obj2, partsList))
                {
                    SuccessJson(String.Format("已完成订单审核."), this.DWZRef);
                }
                else {
                    ErrorJson("提交订单审核失败！");
                }
            }
            else
            {
                if (AgentPartOrderController.Edit(obj2, partsList))
                {
                    SuccessJson(String.Format("已对订单进行修改."), this.DWZRef);
                }
                else {
                    ErrorJson("提交订单进行修改失败！");
                }
            }
        }

        private void recheck()
        {
            string ReCheckRemark = GetRequestValue<string>("ReCheckRemark", "");
            string OrderState = "再确认";
            if (AgentPartOrderController.ReCheck(OrderId, ReCheckRemark, OrderState))
            {
                SuccessJson(String.Format("订单已提交再确认."), this.DWZRef);
            }
            else {
                ErrorJson("提交再确认失败！");
            }

        }
        private void cancel()
        {
            if (AgentPartOrderController.Cancel(OrderId))
            {
                SuccessJson(String.Format("已取消订单."), this.DWZRef);
            }
            else {
                ErrorJson("取消订单失败！");
            }
        }


    }
}